<template>
  <div class="main">
    <div class="title">
      <h2 style="text-align: center">网吧管理系统</h2>
    </div>
    <div>
      <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="60px" class="demo-ruleForm">
        <el-form-item label="账号" prop="username">
          <el-input v-model="ruleForm.username" type="" placeholder="admin" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password" type="password" placeholder="123456" autocomplete="off" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { FormInstance } from 'element-plus'
import { Login } from '../../type/login'
import { login } from '../../api/api'
import { useRouter } from 'vue-router'
const ruleForm = reactive<Login.ReqLoginForm>({
  username: '',
  password: '',
})

const rules = reactive({
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 10, message: '账号的长度在3-10之间', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 10, message: '密码的长度在3-10之间', trigger: 'blur' },
  ],
})
const ruleFormRef = ref<FormInstance>()
const router = useRouter()
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  //validate方法对表单进行验证，返回一个promise对象
  //vaild是返回的布尔值
  formEl.validate((valid) => {
    if (valid) {
      login(ruleForm).then((res) => {
        console.log(res)
        debugger
        localStorage.setItem('token', res.data.token)
        router.push('/')
      })
    } else {
      console.log('error submit!')
      return false
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style scoped lang="less">
.main {
  margin: 0;
  position: fixed;
  background: url(../../assets/bg.jpg) no-repeat;
  background-size: 100% 100%;
  background-size: cover;
  background-position: center;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  min-width: 1600px;
  z-index: -10;
  zoom: 1;
  overflow: hidden;
  .title {
    margin-top: 100px;
  }
  .demo-ruleForm {
    width: 350px;
    margin: 100px auto;
    padding: 30px;
  }
}
</style>
